package com.sfzd5.mistakesbook;

import android.app.Application;
import android.content.SharedPreferences;

import com.sfzd5.mistakesbook.db.DBHelper;
import com.sfzd5.mistakesbook.db.Exam;
import com.sfzd5.mistakesbook.db.Knowledge;
import com.sfzd5.mistakesbook.db.Mistakes;
import com.sfzd5.mistakesbook.db.Student;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MistakesApplication extends Application {

    public Mistakes curEditMistakes;
    public ArrayList<Exam> examList;
    public ArrayList<Student> studentList;
    public ArrayList<Knowledge> knowledgeList;

    public void topExam(Exam ex){
        int fi = -1;
        for(int i=0; i<examList.size(); i++){
            Exam exam = examList.get(i);
            if(ex.id==exam.id){
                fi = i;
                break;
            }
        }
        Exam exam = examList.remove(fi);
        examList.add(0, exam);
    }

    public void topKnowledge(Knowledge kn){
        int fi = -1;
        for(int i=0; i<knowledgeList.size(); i++){
            Knowledge knowledge = knowledgeList.get(i);
            if(kn.id==knowledge.id){
                fi = i;
                break;
            }
        }
        Knowledge knowledge = knowledgeList.remove(fi);
        knowledgeList.add(0, knowledge);
    }

    public void topStudent(Student stu){
        int fi = -1;
        for(int i=0; i<studentList.size(); i++){
            Student student = studentList.get(i);
            if(stu.id==student.id){
                fi = i;
                break;
            }
        }
        Student student = studentList.remove(fi);
        studentList.add(0, student);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        try {
            examList = (ArrayList<Exam>) DBHelper.getInstance(this).getExamDao().queryBuilder().orderBy("id", false).query();
            studentList = (ArrayList<Student>)  DBHelper.getInstance(this).getStudentDao().queryBuilder().orderBy("id", false).query();
            knowledgeList = (ArrayList<Knowledge>)  DBHelper.getInstance(this).getKnowledgeDao().queryBuilder().orderBy("id", false).query();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    public void saveGrade(int grade){
        SharedPreferences preferences = getSharedPreferences("mistakes_setting", this.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putInt("grade", grade);
        editor.commit();
    }

    public int readGrade(){
        SharedPreferences preferences = getSharedPreferences("mistakes_setting", this.MODE_PRIVATE);
        int grade = preferences.getInt("grade", 2021);
        return grade;
    }
}
